package com.zdxlz.fcmp.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdxlz.fcmp.business.dto.IpsecVpnTemplateConfigDto;
import com.zdxlz.fcmp.business.entity.IpsecVpnConfigEntity;
import com.zdxlz.fcmp.business.entity.IpsecVpnTemplateConfigEntity;
import com.zdxlz.fcmp.business.mapper.IpsecVpnConfigMapper;
import com.zdxlz.fcmp.business.mapper.IpsecVpnTemplateConfigMapper;
import com.zdxlz.fcmp.business.service.IIpsecVpnTemplateConfigService;
import com.zdxlz.fcmp.business.vo.IpsecVpnTemplateConfigVo;
import com.zdxlz.fcmp.common.core.exception.BizException;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.zdxlz.fcmp.common.core.constant.enums.ResCode.*;

/**
 * <p>
 * IPSec模板配置表  服务实现类
 * </p>
 *
 * @author: aman
 * @since 2025-02-08
 */
@Service
public class IIpsecVpnTemplateConfigServiceImpl extends ServiceImpl<IpsecVpnTemplateConfigMapper, IpsecVpnTemplateConfigEntity> implements IIpsecVpnTemplateConfigService {

    @Resource
    private IpsecVpnConfigMapper ipsecVpnConfigMapper;

    /**
     * @description 分页查询VPN模板信息列表
     * @author aman
     * @date 2025/2/11 16:25
     */
    @Override
    public IPage<IpsecVpnTemplateConfigVo> getList(Page<IpsecVpnTemplateConfigEntity> page, IpsecVpnTemplateConfigDto vpnTemplateConfigDto) {
        LambdaQueryWrapper<IpsecVpnTemplateConfigEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtils.isNotEmpty(vpnTemplateConfigDto)) {
            queryWrapper
                    .eq(StrUtil.isNotBlank(vpnTemplateConfigDto.getName()), IpsecVpnTemplateConfigEntity::getName, vpnTemplateConfigDto.getName())
                    .eq(ObjectUtil.isNotEmpty(vpnTemplateConfigDto.getEncapsulationMode()), IpsecVpnTemplateConfigEntity::getEncapsulationMode, vpnTemplateConfigDto.getEncapsulationMode());
        }
        Page<IpsecVpnTemplateConfigEntity> vpnTemplateConfigPage = baseMapper.selectPage(page, queryWrapper);

        List<IpsecVpnTemplateConfigVo> templateConfigVoList = vpnTemplateConfigPage.getRecords().stream().map(this::convertToIpsecVpnTemplateConfigVo).collect(Collectors.toList());
        IPage<IpsecVpnTemplateConfigVo> templateConfigVoPage = new Page<>(vpnTemplateConfigPage.getCurrent(), vpnTemplateConfigPage.getSize(), vpnTemplateConfigPage.getTotal());
        templateConfigVoPage.setRecords(templateConfigVoList);
        return templateConfigVoPage;
    }

    /**
     * @description：获取所有VPN模板信息
     * @author：aman
     * @date：2025/2/14 11:24
     */
    @Override
    public List<IpsecVpnTemplateConfigVo> getAllList() {
        List<IpsecVpnTemplateConfigEntity> ipsecVpnTemplateConfigEntities = baseMapper.selectList(null);
        return ipsecVpnTemplateConfigEntities.stream().map(this::convertToIpsecVpnTemplateConfigVo).toList();
    }

    /**
     * @description：新建VPN模板信息
     * @author：aman
     * @date：2025/2/14 11:23
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createIpsecVpnTemplateConfig(IpsecVpnTemplateConfigEntity vpnTemplateConfig) {
        verifyVpnTemplateNameRepeat(vpnTemplateConfig);
        baseMapper.insert(vpnTemplateConfig);
        return true;
    }

    /**
     * @description：通过VPN模板ID更新模板信息
     * @author：aman
     * @date：2025/2/14 11:20
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateIpsecVpnTemplateConfig(IpsecVpnTemplateConfigEntity vpnTemplateConfig) {
        verifyVpnTemplateNameRepeat(vpnTemplateConfig);

        Map<String, Object> queryPara = Map.of("ipsec_template_id", vpnTemplateConfig.getId(), "enable", Boolean.TRUE);
        List<IpsecVpnConfigEntity> vpnConfigEntityList = ipsecVpnConfigMapper.selectByMap(queryPara);
        List<IpsecVpnConfigEntity> configList = vpnConfigEntityList.stream().filter(entity -> entity.getEnable().equals(vpnTemplateConfig.getDpdEnable())).toList();
        if (CollectionUtil.isNotEmpty(configList))
            throw new BizException(VPN_TEMPLATE_USED_NO_UPDATE.getCode(), VPN_TEMPLATE_USED_NO_UPDATE.getReason());
        baseMapper.updateById(vpnTemplateConfig);
        return true;
    }

    /**
     * @description：通过VPN模板ID删除模板信息
     * @author：aman
     * @date：2025/2/14 11:20
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteIpsecVpnTemplateConfig(List<Integer> ids) {
        Integer temId = ids.get(0);
        IpsecVpnTemplateConfigEntity entity = baseMapper.selectById(temId);
        if (ObjectUtil.isNotEmpty(entity)) {
            Map<String, Object> queryPara = Map.of("ipsec_template_id", temId);
            List<IpsecVpnConfigEntity> vpnConfigEntityList = ipsecVpnConfigMapper.selectByMap(queryPara);
            if (CollectionUtil.isNotEmpty(vpnConfigEntityList))
                throw new BizException(VPN_TEMPLATE_USED_NO_DELETE.getCode(), VPN_TEMPLATE_USED_NO_DELETE.getReason());
            baseMapper.deleteByIds(ids);
            return true;
        }
        throw new BizException(VPN_TEMPLATE_NOT_EXIST.getCode(), VPN_TEMPLATE_NOT_EXIST.getReason());
    }

    /**
     * @description Vpn模板实体转换为Vpn模板响应实体
     * @author aman
     * @date 2025/2/11 16:25
     */
    private IpsecVpnTemplateConfigVo convertToIpsecVpnTemplateConfigVo(IpsecVpnTemplateConfigEntity vpnTemplateConfig) {
        IpsecVpnTemplateConfigVo templateConfigVo = new IpsecVpnTemplateConfigVo();
        BeanUtil.copyProperties(vpnTemplateConfig, templateConfigVo);
        return templateConfigVo;
    }

    /**
     * @description：校验Vpn模板名称是否重复
     * @author：aman
     * @date：2025/2/14 17:41
     */
    private void verifyVpnTemplateNameRepeat(IpsecVpnTemplateConfigEntity vpnTemplateConfig) {
        Map<String, Object> oneEntity = Map.of("name", vpnTemplateConfig.getName());
        List<IpsecVpnTemplateConfigEntity> ipsecVpnTemplateConfigEntities = baseMapper.selectByMap(oneEntity);
        List<IpsecVpnTemplateConfigEntity> configEntities = ipsecVpnTemplateConfigEntities.stream().filter(entity -> !entity.getId().equals(vpnTemplateConfig.getId())).toList();
        if (CollectionUtil.isNotEmpty(configEntities))
            throw new BizException(VPN_TEMPLATE_NAME_IS_DUPLICATED.getCode(), VPN_TEMPLATE_NAME_IS_DUPLICATED.getReason());
    }
}
